package com.example.blemulticondemo.adapter;

import android.bluetooth.BluetoothDevice;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.blemulticondemo.BleManager;
import com.example.blemulticondemo.R;

import java.util.List;

/**
 * @author linvisf
 * @date 2024/8/6.
 * description：
 */
public class BleDeviceAdapter extends RecyclerView.Adapter<BleDeviceAdapter.ViewHolder> {
    private List<BluetoothDevice> deviceList;
    private BleManager bleManager;

    public BleDeviceAdapter(List<BluetoothDevice> deviceList, BleManager bleManager) {
        this.deviceList = deviceList;
        this.bleManager = bleManager;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_ble_list_item, parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BluetoothDevice device = deviceList.get(position);
        holder.tvName.setText(device.getName());
        holder.tvMac.setText(device.getAddress());
        if (bleManager.isDeviceConnected(device)) {
            holder.btnConnect.setText("已连接");
            holder.btnConnect.setBackgroundResource(R.drawable.btn_bg);
        } else {
            holder.btnConnect.setText("未连接");
            holder.btnConnect.setBackgroundResource(R.drawable.btn_bg_disconnect);
        }

        holder.btnConnect.setOnClickListener(v -> {
            if (bleManager.isDeviceConnected(device)) {
                bleManager.disconnect(device);
                holder.btnConnect.setText("未连接");
                holder.btnConnect.setBackgroundResource(R.drawable.btn_bg_disconnect);
            } else {
                bleManager.connectDevice(device);
                holder.btnConnect.setText("已连接");
                holder.btnConnect.setBackgroundResource(R.drawable.btn_bg);
            }
        });
    }

    @Override
    public int getItemCount() {
        return deviceList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;
        TextView tvMac;
        Button btnConnect;

        public ViewHolder(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_device_name);
            tvMac = itemView.findViewById(R.id.tv_device_address);
            btnConnect = itemView.findViewById(R.id.btnConnect);
        }
    }
}
